#include "esp_log.h"
#include "string"
#include "nvs_flash.h"
#include "nvs.h"
#include "my_events.h"
#include "esp_random.h"
#include "btn.h"
// #include "led.h"
#include "ledc.h"
#include "my_timer.h"
#include "my_uart.h"
#include "esp_gdbstub.h"

static const char *TAG = "MAIN";

extern "C" void app_main(void)
{
    init_uart();
    // esp_gdbstub_init();
    initBtns();
    // 1. 初始化 NVS
    esp_err_t nvs_ret = nvs_flash_init();
    if (nvs_ret == ESP_ERR_NVS_NO_FREE_PAGES || nvs_ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        nvs_ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(nvs_ret);

    init_event_loop();
    ledc_init();

    esp_event_handler_register_with(
        my_event_loop_handle,
        MY_EVENT_BASE,
        MY_EVENT_ID_HELLO,
        [](void *handler_args, esp_event_base_t base, int32_t id, void *data)
        {
            ESP_LOGI(TAG, "Hello event received, id=%ld, data: %s", id, (char *)data);
        },
        nullptr);

    std::string msg = "Hello, ESP-IDF, my random id is " + std::to_string(esp_random());

    esp_event_post_to(my_event_loop_handle,
                      MY_EVENT_BASE,     // event_base
                      MY_EVENT_ID_HELLO, // event_id
                      (void *)(msg.c_str()),       // event_data
                      msg.size() + 1,
                      portMAX_DELAY);

    init_timers();
}
